package watch

import (
	"coding.net/vco/mder/modules/coding"
	"coding.net/vco/mder/modules/log"
	"coding.net/vco/mder/modules/util"
	"fmt"
	"github.com/Unknwon/com"
	"github.com/howeyc/fsnotify"
	"strings"
	"time"
)

const (
	//watch_dir     = "markdown"
	temp_ext      = ".tmp"
	rebuild_delay = 1500
)

var (
	lastBuild time.Time
)

func Run() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal("Fail to create new watcher: %v", err)
	}
	watch_dir := coding.DATA_PATH
	dirs, _ := com.GetAllSubDirs(watch_dir)
	watchDirs := append(dirs, watch_dir)
	for _, dir := range watchDirs {
		if dir != watch_dir {
			dir = fmt.Sprintf("%s/%s", watch_dir, dir)
		}

		err = watcher.Watch(dir)
		if err != nil {
			log.Fatal("Fail to watch diretory(%s): %v", dir, err)
		}
	}

	go func() {
		for {
			select {
			case e := <-watcher.Event:
				log.Debug(e.Name)
				if isTempFile(e.Name) || !hasWatchExt(e.Name) {
					continue
				}

				if lastBuild.Add(time.Duration(rebuild_delay) * time.Millisecond).
					After(time.Now()) {
					continue
				}
				lastBuild = time.Now()
				//重新为当前文件生成临时文件
				coding.FetchMdFile(e.Name)
			}

		}
	}()
}

//只监视md变化
func hasWatchExt(name string) bool {
	return util.IsMd(name)
}

func isTempFile(name string) bool {
	return strings.HasSuffix(name, temp_ext)
}
